import {currentUser, currentUser as queryCurrentUser, loginByPassword} from '@/api/user';
import {LoginForm, ProFormCaptcha, ProFormText,} from '@ant-design/pro-components';
import {useEmotionCss} from '@ant-design/use-emotion-css';
import {Helmet, useModel,history} from '@umijs/max';
import {message, Tabs} from 'antd';
import React, {useState} from 'react';
import {flushSync} from "react-dom";

type LoginType = 'phone' | 'account';
const Login: React.FC = () => {
    const containerClassName = useEmotionCss(() => {
        return {
            display: 'flex',
            flexDirection: 'column',
            height: '100vh',
            overflow: 'auto',
            backgroundImage:
                "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
            backgroundSize: '100% 100%',
        };
    });
    const [loginType, setLoginType] = useState<LoginType>('account');
    const {initialState, setInitialState} = useModel('@@initialState');

    // 获取用户信息
    const fetchUserInfo = async (data) => {
        console.log('fetchUserInfo-initialState---', initialState)
        // const userInfo = await initialState?.fetchUserInfo?.();
        const res = await queryCurrentUser({userId: data.userId})

        if (res.data) {
            flushSync(() => {
                setInitialState((s) => ({
                    ...s,
                    ...data,
                    currentUser: res.data,
                }));
                console.log('--initialState--',initialState)
                console.log('--setInitialState--',setInitialState)
                localStorage.setItem('currentUser',JSON.stringify({
                    currentUser: res.data,
                }))
            });
            history.push('/')
        }

    }

    // 登录
    const handleSubmit = async (values) => {
        const res = await loginByPassword(values);
        if (res.data) {
            localStorage.setItem('token', res.data.token)
            await fetchUserInfo(res.data);
        }
    };
    return (
        <div className={containerClassName}>
            <Helmet>
                <title>登录页 - zero</title>
            </Helmet>

            <div
                style={{
                    flex: '1',
                    padding: '32px 0',
                }}
            >
                <LoginForm
                    contentStyle={{
                        minWidth: 280,
                        maxWidth: '75vw',
                    }}
                    title="登录页面"
                    subtitle="Login in"
                    onFinish={async (values) => {
                        await handleSubmit(values);
                    }}
                >
                    {loginType}---
                    <Tabs
                        centered
                        activeKey={loginType}
                        onChange={(activeKey) => setLoginType(activeKey as LoginType)}
                        items={[
                            {
                                key: 'account',
                                label: '账户密码登录',
                            },
                            {
                                key: 'phone',
                                label: '手机号登录',
                            },
                        ]}
                    />
                    {loginType === 'account' && (
                        <>
                            <ProFormText
                                name="username"
                                placeholder="用户名: admin or user"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入用户名!',
                                    },
                                ]}
                            />
                            <ProFormText.Password
                                name="password"
                                placeholder={'密码: ant.design'}
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入密码！',
                                    },
                                ]}
                            />
                        </>
                    )}
                    {loginType === 'phone' && (
                        <>
                            <ProFormText
                                name="mobile"
                                placeholder={'手机号'}
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入手机号！',
                                    },
                                    {
                                        pattern: /^1\d{10}$/,
                                        message: '手机号格式错误！',
                                    },
                                ]}
                            />
                            <ProFormCaptcha
                                captchaProps={{
                                    size: 'large',
                                }}
                                placeholder={'请输入验证码'}
                                captchaTextRender={(timing, count) => {
                                    if (timing) {
                                        return `${count} ${'获取验证码'}`;
                                    }
                                    return '获取验证码';
                                }}
                                name="captcha"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入验证码！',
                                    },
                                ]}
                                onGetCaptcha={async () => {
                                    message.success('获取验证码成功！验证码为：1234');
                                }}
                            />
                        </>
                    )}
                </LoginForm>
            </div>
        </div>
    );
};

export default Login;
